package com.ws.gc.web.auth.handler;

import com.ws.rain.base.utils.encrypt.Base64Util;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.net.URLEncoder;

@Component
public class AuthSuccessHandler implements ServerAuthenticationSuccessHandler {

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange filterExchange, Authentication authentication) {
        ServerHttpResponse response = filterExchange.getExchange().getResponse();
        response.getHeaders().add("Content-Type", "application/json; charset=UTF-8");
        String url = "/user/success?username="+URLEncoder.encode(Base64Util.encode(authentication.getName()));
        URI uri = URI.create(url);
        response.getHeaders().setLocation(uri);
        response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
        return response.writeWith(Mono.empty());
    }
}
